package cn.sc.allinpay.allfavour.base.connect.http;

import android.content.Intent;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.pai.connect.http.request.OkRequest;
import cn.pai.connect.http.respcall.JsonRespCall;
import cn.sc.allinpay.allfavour.app.App;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.business.common.app.Global;
import cn.sc.allinpay.allfavour.business.common.data.SpToken;
import cn.sc.allinpay.allfavour.business.common.utils.SpUtils;
import okhttp3.CacheControl;

import static cn.sc.allinpay.allfavour.app.App.getContext;

/**
 * 应用请求
 * author：pany
 * on 2017/12/1 14:59
 */
public class AppRequest extends OkRequest {

    private StringBuffer urlBuffer;

    public AppRequest baseUrl(String url) {
        urlBuffer = new StringBuffer(url);
        return this;
    }

    public AppRequest action(String action) {
        url(urlBuffer.append(action).toString());
        cache(new CacheControl.Builder().noCache().build());// 设置无缓存
        return this;
    }

    /**
     * 平台服务器定制回调
     *
     * @author pany 2017年7月24日
     */
    public static abstract class RequestCall extends JsonRespCall {

        @Override
        public void onResponse(JSONObject response) {
            if ("0000".equals(response.getString("code"))) {
                onSuccess(response);
            } else {
                onFailure(response, response.getString("msg"));
            }
        }

        protected abstract void onSuccess(JSONObject response);
    }

    /**
     * 平台服务器定制回调
     *
     * @author pany 2017年7月24日
     */
    public static abstract class PosRequestCall extends JsonRespCall {

        @Override
        public void onResponse(JSONObject response) {
            if (response.getIntValue("code") == 0) {
                if (response.getString("token") != null) {
                    Global global = Global.getInstance();
                    SpToken token = new SpToken();
                    token.setToken(response.getString("token"));
                    global.setToken(token);
                    SpUtils.put(getContext(), Constant.SPNAME, Constant.SpKey.Token, JSON.toJSONString(token));
                }
                onSuccess(response);
            } else if (response.getIntValue("code") == 1){
                Toast.makeText(App.getContext(), "登录失效,请重新登录",
                        Toast.LENGTH_SHORT).show();
                App.getContext().sendBroadcast(new Intent(Constant.Action.ACTION_CASHIER_LOGIN_OUT));
            }else {
                onFailure(response, response.getString("message"));
            }
        }

        protected abstract void onSuccess(JSONObject response);
    }
}
